from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
#  ==========================  配置 ==============================
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

secret_id = 'AKIDHI3cu67d4i6C3PzKwuc7MMhlZ6N6vw0O'      # 替换为用户的 secretId
secret_key = 'BBvPjmZ8VdZFfspVv97tOdcNyIRK3Vhi'      # 替换为用户的 secretKey
region = 'ap-beijing'     # 替换为用户的 Region

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
# 2. 获取客户端对象
client = CosS3Client(config)
#  ==========================  创建一个桶 ==============================
def create_bucket(bucked):
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    secret_id = 'AKIDHI3cu67d4i6C3PzKwuc7MMhlZ6N6vw0O'  # 替换为用户的 secretId
    secret_key = 'BBvPjmZ8VdZFfspVv97tOdcNyIRK3Vhi'  # 替换为用户的 secretKey
    region = 'ap-beijing'  # 替换为用户的 Region

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)

    response = client.create_bucket(
        Bucket=bucked,  # 1302094470 这个是我的appid  后缀这里必须加
        ACL='public-read'  # private/ public-read/ public-read-write    私有读写  共有读私有写  公共读写

    )
    # 下面的是要配置桶 可以实现跨站访问

    cors_config = {
        'CORSRule': [
            {
                # 'ID': '1234',
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'POST', 'HEAD', 'DELETE'],
                'AllowedHeader': '*',
                'ExposeHeader': '*',
                'MaxAgeSeconds': 500
            }
        ]
    }
    response = client.put_bucket_cors(
        Bucket=bucked,
        CORSConfiguration=cors_config
    )

#  ==========================  上传一个文件 ==============================
# response1 = client.upload_file_from_buffer(
#         Bucket='{0}'.format(Bucket),  # request.obj.0.0   桶的名字
#         Body=img_path,  # img_object = request.EILES.get('editormd-image-file') 要上传的文件对象  要上传的文件对象
#         Key=key    # 名字
#
#     )
#  ==========================  删除一个文件 ==============================
def delete_file(bucket, key):
    """

    :param bucket: 桶的名字    8-1302094470
    :param key:   图片的名字   1590498110.92144.png
    :return: None
    """
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    client.delete_object(
        Bucket=bucket,
        Key=key
    )
